<template>
  <guat-page-layout divide :title="['值日安排']">
    <template #actions>
      <guat-button-group
        :buttons="[{ text: '保存安排', internal: $config.$button.PLR, onClick: handleSaveArrange }]"
      />
    </template>
    <template #left>
      <div class="flex flex-col gap-4">
        <a-card title="查找成员" :bordered="false">
          <guat-search-form />
          <template #actions>
            <guat-button-group :buttons="[{ text: '重置' }, { text: '查找', type: 'primary' }]" />
          </template>
        </a-card>
        <a-card title="成员列表" :bordered="false">
          <a-scrollbar style="height: 447px; overflow: auto">
            <div class="grid grid-cols-2 gap-4">
              <a-tooltip v-for="member in members" :content="`学号：${member.userNo}`">
                <div
                  class="flex items-center justify-between h-11 px-3 rounded bg-primary-light-1 hover:bg-primary-light-2 active:bg-primary-light-3 cursor-move"
                  draggable="true"
                  @dblclick="handleBatchArrange(member)"
                  @dragstart="handleOnDragStart(member, $event)"
                  @dragend="handleOnDragEnd"
                >
                  <a-tag color="#63b2ff" class="min-w-[66px] justify-center !text-sm">
                    {{ member.userName }}
                  </a-tag>
                  <span class="text-primary"> 已安排：{{ arrange[member[MPM.No]] ?? 0 }}日 </span>
                </div>
              </a-tooltip>
            </div>
          </a-scrollbar>
        </a-card>
      </div>
    </template>
    <template #right>
      <a-card :bordered="false">
        <div class="flex flex-col gap-4">
          <div class="flex items-center justify-between mb-4">
            <div class="flex items-center gap-5 text-[28px] select-none">
              <div>{{ monthChinese }}</div>
              <div class="text-[#bfbfbf]">{{ year }}</div>
            </div>
          </div>
          <div class="flex flex-col border border-[#e5e6eb]">
            <div class="grid grid-cols-7 border-b border-[#e5e6eb] last:border-none">
              <div
                class="h-8 text-center leading-8 border-r border-[#e5e6eb] last:border-none select-none"
                v-for="day in ['日', '一', '二', '三', '四', '五', '六']"
              >
                星期{{ day }}
              </div>
            </div>
            <div
              class="grid grid-cols-7 border-b border-[#e5e6eb] last:border-none"
              v-for="week in weeks"
            >
              <div
                v-for="date in week"
                class="flex flex-col min-h-[128px] p-2 border-r border-[#e5e6eb] [&:nth-child(7)]:border-none"
                :class="{ 'bg-primary-light-1': currentOver == date.dateString }"
                :data-date="date.dateString"
                @dragenter.prevent="handleOnDragEnter"
                @dragover.prevent="handleOnDragOver"
                @drop="handleOnDrop"
              >
                <div class="select-none">{{ date.dateString }}</div>
                <div class="flex flex-wrap gap-2 mt-2">
                  <a-tag
                    v-for="member in data[date.dateString]"
                    class="cursor-pointer select-none hover:opacity-80"
                    color="blue"
                    @dblclick="handleOnDoubleClick(date.dateString, member)"
                  >
                    {{ member.userName }}
                  </a-tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-card>
    </template>
    <guat-arrange-modal title="值日安排" @ok="handleArrange">
      <TestForm />
    </guat-arrange-modal>
  </guat-page-layout>
</template>

<script setup lang="ts">
import { searchFormItemConfig, arrangeFormConfig } from "../form-config";
import { isEqual } from "lodash-es";
import { MemberPropertyMap as MPM } from "@/map/member/property-map";

interface A {
  [MPM.No]: string | number;
  [MPM.Name]: string;
}
const [TestForm, { setFormValue, getFormValue }] = useForm(arrangeFormConfig);
const [GuatSearchForm] = useForm(searchFormItemConfig);
const [GuatArrangeModal, { setModalVisible }] = useModal();
const { year, weeks, monthChinese } = useCalender();
const { success } = useMessage();

const currentOver = ref();
const currentDragMember = ref<Nullable<A>>();
const currentArrangeMember = ref<A>();

const members: A[] = [
  { userNo: "2022070030101", userName: "史伟超" },
  { userNo: "2022070030102", userName: "杨敏" },
  { userNo: "2022070030103", userName: "何敏文" },
  { userNo: "2022070030104", userName: "张洋阳" },
  { userNo: "2022070030105", userName: "吴梦娜" },
  { userNo: "2022070030106", userName: "江军" },
  { userNo: "2022070030107", userName: "胡小娟" },
  { userNo: "2022070030108", userName: "贺礼杰" },
  { userNo: "2022070030109", userName: "邱娜" },
  { userNo: "2022070030110", userName: "朱艳" },
  { userNo: "2022070030110", userName: "朱艳" },
  { userNo: "2022070030110", userName: "朱艳" },
  { userNo: "2022070030110", userName: "朱艳" },
];
const arrange = reactive<Recordable<number>>({});
const data = reactive<Recordable<A[]>>({});

const handleOnDragStart = (member: A, e: DragEvent) => {
  e.dataTransfer!.effectAllowed = "move";
  currentDragMember.value = member;
};

const handleOnDragEnd = () => {
  currentOver.value = "";
  currentDragMember.value = null;
};

const handleOnDragEnter = (e: DragEvent) => {
  e.dataTransfer!.dropEffect = "move";
  currentOver.value = getArrangeContainer(e.target as HTMLDivElement)?.dataset.date;
};

const handleOnDragOver = (e: DragEvent) => {
  e.dataTransfer!.dropEffect = "move";
};

const handleOnDrop = () => {
  arrangeMember(unref(currentDragMember)!, unref(currentOver));
  currentOver.value = "";
};

const handleOnDoubleClick = (date: string, member: A) => {
  data[date] = data[date].filter((record) => !isEqual(record, member));
  const no = member[MPM.No];
  arrange[no!]--;
};

const handleBatchArrange = (member: A) => {
  currentArrangeMember.value = member;
  setFormValue({
    name: "李四",
    no: "2020070030506",
    arrange: 10,
  });
  setModalVisible(true);
};

const handleSaveArrange = () => {
  console.log(data);
  success("保存成功");
};

const getArrangeContainer = (node: HTMLDivElement) => {
  let _node = node;
  while (_node) {
    if (_node.dataset.date) return _node;
    _node = (_node as HTMLDivElement).parentNode as HTMLDivElement;
  }
};

function arrangeMember(member: A, date: string) {
  if (data[date]) {
    if (!data[date].includes(member)) {
      data[date].push(member);
      arrange[member[MPM.No]] = (arrange[member[MPM.No]] ?? 0) + 1;
    }
  } else {
    data[date] = [member];
    arrange[member[MPM.No]] = (arrange[member[MPM.No]] ?? 0) + 1;
  }
}

function handleArrange() {
  const date: string[] = (getFormValue() as any).dateRange;
  const start = new Date(date[0]);
  const end = new Date(date[1]);
  const member = unref(currentArrangeMember);

  while (start <= end) {
    const dateString = start.toISOString().split("T")[0];
    arrangeMember(member!, dateString);
    start.setDate(start.getDate() + 1);
  }
}
</script>

<style scoped>
:deep(.arco-calendar-month-row) {
  height: auto;
  min-height: 100px;
}
</style>
